package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.IpAddressManager;
import com.anne.fish.model.IpAddress;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class IpAddressAction extends BaseAction implements Preparable {
    private IpAddressManager ipAddressManager;
    private List ipAddresses;
    private IpAddress ipAddress;
    private Long id;
    private String query;

    public void setIpAddressManager(IpAddressManager ipAddressManager) {
        this.ipAddressManager = ipAddressManager;
    }

    public List getIpAddresses() {
        return ipAddresses;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String ipAddressId = getRequest().getParameter("ipAddress.id");
            if (ipAddressId != null && !ipAddressId.equals("")) {
                ipAddress = ipAddressManager.get(new Long(ipAddressId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        ipAddresses = ipAddressManager.search(query, IpAddress.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public IpAddress getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(IpAddress ipAddress) {
        this.ipAddress = ipAddress;
    }

    public String delete() {
        ipAddressManager.remove(ipAddress.getId());
        saveMessage(getText("ipAddress.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            ipAddress = ipAddressManager.get(id);
        } else {
            ipAddress = new IpAddress();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (ipAddress.getId() == null);

        ipAddressManager.save(ipAddress);

        String key = (isNew) ? "ipAddress.added" : "ipAddress.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}